#include "Ze08Ch2o.h"

/*宏定义*/
#define SERIAL1_RX 27
#define SERIAL1_TX 14

/*全局变量*/
int ppb = 0;//气体浓度值
extern volatile uint8_t manual_open_fan_flag;//风扇自动侦测标志 
                                             //0-自动侦测关闭 1--自动侦测开启 2--自动侦测暂时关闭10分钟后开启
extern volatile uint8_t fan_switch;//风扇开关标志 0--关闭 1--开启
extern volatile uint8_t pm25_flag;//风扇根据PM2.5而开启关闭 0--关闭 1--开启
volatile uint8_t ppb_flag = 0;//风扇根据甲醛而开启关闭 0--关闭 1--开启

/*全局函数*/
void Ze08_Ch2o_Init(void)
{
    Serial1.begin(9600, SERIAL_8N1, SERIAL1_RX, SERIAL1_TX);

    Serial.println("Ze08_Ch2o_Init success");
}

void Read_Ze08_Ch2o_Data(void)
{
    static uint8_t idx = 0;
    uint8_t i;
    uint8_t j = 0;
    float ppm;
    float ch2o;

    char ze08_ch2o_data[9];
    memset(ze08_ch2o_data,'\0',sizeof(ze08_ch2o_data));

    //Serial.println("hahaha");

    i = Serial1.available();

    if(i == 9)//接收到完整的ZE08CH2O传感器发过来的完整的一帧数据
    {
        while(i--)
        {
            ze08_ch2o_data[j] = Serial1.read();
            j++;
        }
        Serial1.flush();


        j = 0;

        if(ze08_ch2o_data[0] == 0xFF)
        {
            // for(i = 0; i < sizeof(ze08_ch2o_data); i++)
            // {
            //     Serial.printf("%x ",ze08_ch2o_data[i]);
            // }
            // Serial.println();

            ppb = ze08_ch2o_data[4] * 256 + ze08_ch2o_data[5];  
            ppm = ppb / 1000.0;
            ch2o = ppm * 1.25;

            //Serial.printf("ppb:%d ppm:%f ch2o:%f\r\n",ppb,ppm,ch2o);
            if(idx > 5)
            {
                Update_PPB_CH2O_To_Aliyun(ppb,ch2o);
                idx = 0;

                if(manual_open_fan_flag == 1)
                {
                    if(ppb >= 100)
                    {
                        if(fan_switch == 0)
                        {
                            Fan_Open();//打开风扇
                            fan_switch = 1;
                        }

                        WS2812B_SetGRB(120, 10, 0);//警戒颜色 红橙色
                        ppb_flag = 1;
                    }
                    else if(ppb < 100)
                    {
                        ppb_flag = 0;
                        
                        if(fan_switch == 1 && pm25_flag == 0)
                        {
                            Fan_Close();
                            fan_switch = 0;
                            WS2812B_Close();//关闭WS2812B灯带
                        }
                    }

                    Update_FanSwitch_To_Aliyun(fan_switch);
                }
                else//手动模式
                {
                    
                }
            }
            else if(idx <= 5)
            {
                idx++;
            } 
        }
    } 
    else if(i > 9)//如果超过完整的一帧数据,就要先把读缓存清除
    {
        while(i--)
        {
            Serial1.read();
        }
        Serial1.flush();
    } 
}